<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 15-1-9
 * Time: 下午4:49
 * 电桩管理
 */
namespace Admin\Controller;
use Mcit\Page;
class EvchargerController extends BaseController {

    //首页
    public function index(){

        $evc_number = I('evc_number');
        $key_link   = I('key_link');
        if(!empty($_SESSION['company'])){
            $company = M("company")->where("id='".$_SESSION['company']."'")->find();
            $re = strsToArray($company['location']);
            $location = $re[0].",".$re[1];

            if(!empty($_GET['evc_number'])){
                $sql = "select * from ev_char a
                left join ev_plant b
                on b.id = a.ev_plant_id
                where a.evc_number like '$evc_number%'
                and b.location like '$location%'";
            }elseif(!empty($_GET['key_link'])){
                $sql = "select * from ev_char a
                left join ev_plant b
                on b.id = a.ev_plant_id
                where a.key_link like '$key_link%'
                and b.location like '$location%'";
            }elseif(!empty($_GET['location_f_1'])){
                if(I('location_s_1') == 110100 || I('location_s_1') == 120100 || I('location_s_1') == 310100 || I('location_s_1') == 500100){
                    if(I('location_s_1') == I('location_t_1')-1){
                        $location = I('location_f_1').",".I('location_s_1');
                    }else{
                        $location = I('location_f_1').",".I('location_s_1').",".I('location_t_1');
                    }
                }else if(I('location_s_1') == I('location_t_1')-1){
                    $location = I('location_f_1').",".I('location_s_1');
                }else{
                    $location = I('location_f_1').",".I('location_s_1').",".I('location_t_1');
                }
                $sql = "select * from ev_char a
                left join ev_plant b
                on b.id = a.ev_plant_id
                where b.location like '$location%'";
            }else{
                $sql = "select * from ev_char a
                left join ev_plant b
                on b.id = a.ev_plant_id
                where b.location like '$location%'";
            }
            //分页
            $count = count(M()->query($sql));
            // 重搜一律回第一页
            if( $_GET['fsign'] == "abnormal" ){
                $_GET['fsign'] = "normal";
                $_GET['page']  = 0;
            }
            vendor('Mcit.Sys.Page');
            $Page = new Page($count, 20);
            $pageView = $Page->show();
            $this->assign('pageView', $pageView); //发送分页
            $nowPage = isset($_GET['page']) ? $_GET['page'] * 20 - 20 : 0;
            if(!empty($_GET['evc_number'])){
                $sql1 = "select a.char_mode, a.id,a.evc_number,a.key_link,a.evc_type,a.card_wifi,a.evc_quantity,a.sys_creat_time,b.name,b.location from ev_char a
                left join ev_plant b
                on b.id = a.ev_plant_id
                where a.evc_number like '$evc_number%'
                and b.location like '$location%'
                limit $nowPage,".$Page->listRows;
            }elseif(!empty($_GET['key_link'])){
                $sql1 = "select a.char_mode, a.id,a.evc_number,a.key_link,a.evc_type,a.card_wifi,a.evc_quantity,a.sys_creat_time,b.name,b.location from ev_char a
                left join ev_plant b
                on b.id = a.ev_plant_id
                where a.key_link like '$key_link%'
                and b.location like '$location%'
                limit $nowPage,".$Page->listRows;
            }elseif(!empty($_GET['location_f_1'])){
                if(I('location_s_1') == 110100 || I('location_s_1') == 120100 || I('location_s_1') == 310100 || I('location_s_1') == 500100){
                    if(I('location_s_1') == I('location_t_1')-1){
                        $location = I('location_f_1').",".I('location_s_1');
                    }else{
                        $location = I('location_f_1').",".I('location_s_1').",".I('location_t_1');
                    }
                }else if(I('location_s_1') == I('location_t_1')-1){
                    $location = I('location_f_1').",".I('location_s_1');
                }else{
                    $location = I('location_f_1').",".I('location_s_1').",".I('location_t_1');
                }
                $sql1 = "select a.char_mode, a.id,a.evc_number,a.key_link,a.evc_type,a.card_wifi,a.evc_quantity,a.sys_creat_time,b.name,b.location from ev_char a
                left join ev_plant b
                on b.id = a.ev_plant_id
                where b.location like '$location%'
                limit $nowPage,".$Page->listRows;
            }else{
                $sql1 = "select a.char_mode, a.id,a.evc_number,a.key_link,a.evc_type,a.card_wifi,a.evc_quantity,a.sys_creat_time,b.name,b.location from ev_char a
                left join ev_plant b
                on b.id = a.ev_plant_id
                where b.location like '$location%'
                limit $nowPage,".$Page->listRows;
            }
            $ev_char = M()->query($sql1);
            //分页结束
            foreach($ev_char as $k=>$v){
                $region_arr = strsToArray($v['location']);//查所在地
                $region = D("Region")->where("code='".$region_arr[2]."'")->getField('fullname');
                $ev_char[$k]['plant_name'] = $v['name'];//站点名称
                if(mb_strlen($v['name'],'utf-8') <= 10){
                    $ev_char[$k]['plant_name_text'] = $v['name'];
                }else{
                    $ev_char[$k]['plant_name_text'] = mb_substr($v['name'],0,10,"utf-8")."···";
                }
                $ev_char[$k]['region_text'] = $region;
            }
            $this->china = D("Admin/Region")->getDowntown($re['0']);//当前省下所有市区县
        }else{
            if(!empty($_GET['evc_number'])){
                $sql = "select * from ev_char a
                left join ev_plant b
                on b.id = a.ev_plant_id
                where a.evc_number like '$evc_number%'";
            }elseif(!empty($_GET['key_link'])){
                $sql = "select * from ev_char a
                left join ev_plant b
                on b.id = a.ev_plant_id
                where a.key_link like '$key_link%'";
            }elseif(!empty($_GET['location_f_1'])){
                if(I('location_s_1') == 110100 || I('location_s_1') == 120100 || I('location_s_1') == 310100 || I('location_s_1') == 500100){
                    if(I('location_s_1') == I('location_t_1')-1){
                        $location = I('location_f_1').",".I('location_s_1');
                    }else{
                        $location = I('location_f_1').",".I('location_s_1').",".I('location_t_1');
                    }
                }else if(I('location_s_1') == I('location_t_1')-1){
                    $location = I('location_f_1').",".I('location_s_1');
                }else{
                    $location = I('location_f_1').",".I('location_s_1').",".I('location_t_1');
                }
                $sql = "select * from ev_char a
                left join ev_plant b
                on b.id = a.ev_plant_id
                where b.location like '$location%'";
            }else{
                $sql = "select * from ev_char a
                left join ev_plant b
                on b.id = a.ev_plant_id";
            }
            //分页
            $count = count(M()->query($sql));
            // 重搜一律回第一页
            if( $_GET['fsign'] == "abnormal" ){
                $_GET['fsign'] = "normal";
                $_GET['page']  = 0;
            }
            vendor('Mcit.Sys.Page');
            $Page = new Page($count, 20);
            $pageView = $Page->show();
            $this->assign('pageView', $pageView); //发送分页
            $nowPage = isset($_GET['page']) ? $_GET['page'] * 20 - 20 : 0;
            if(!empty($_GET['evc_number'])){
                $sql1 = "select a.char_mode, a.id,a.evc_number,a.key_link,a.evc_type,a.card_wifi,a.evc_quantity,a.sys_creat_time,b.name,b.location from ev_char a
                left join ev_plant b
                on b.id = a.ev_plant_id
                where a.evc_number like '$evc_number%'
                limit $nowPage,".$Page->listRows;
            }elseif(!empty($_GET['key_link'])){
                $sql1 = "select a.char_mode, a.id,a.evc_number,a.key_link,a.evc_type,a.card_wifi,a.evc_quantity,a.sys_creat_time,b.name,b.location from ev_char a
                left join ev_plant b
                on b.id = a.ev_plant_id
                where a.key_link like '$key_link%'
                limit $nowPage,".$Page->listRows;
            }elseif(!empty($_GET['location_f_1'])){
                if(I('location_s_1') == 110100 || I('location_s_1') == 120100 || I('location_s_1') == 310100 || I('location_s_1') == 500100){
                    if(I('location_s_1') == I('location_t_1')-1){
                        $location = I('location_f_1').",".I('location_s_1');
                    }else{
                        $location = I('location_f_1').",".I('location_s_1').",".I('location_t_1');
                    }
                }else if(I('location_s_1') == I('location_t_1')-1){
                    $location = I('location_f_1').",".I('location_s_1');
                }else{
                    $location = I('location_f_1').",".I('location_s_1').",".I('location_t_1');
                }
                $sql1 = "select a.char_mode, a.id,a.evc_number,a.key_link,a.evc_type,a.card_wifi,a.evc_quantity,a.sys_creat_time,b.name,b.location from ev_char a
                left join ev_plant b
                on b.id = a.ev_plant_id
                where b.location like '$location%'
                limit $nowPage,".$Page->listRows;
            }else{
                $sql1 = "select a.char_mode, a.id,a.evc_number,a.key_link,a.evc_type,a.card_wifi,a.evc_quantity,a.sys_creat_time,b.name,b.location from ev_char a
                left join ev_plant b
                on b.id = a.ev_plant_id
                limit $nowPage,".$Page->listRows;
            }
            $ev_char = M()->query($sql1);
//            echo M()->getLastSql();
//            P($ev_char);
            //分页结束
            foreach($ev_char as $k=>$v){
                $region_arr = strsToArray($v['location']);//查所在地
                $region = D("Region")->where("code='".$region_arr[2]."'")->getField('fullname');
                $ev_char[$k]['plant_name'] = $v['name'];//站点名称
                if(mb_strlen($v['name'],'utf-8') <= 10){
                    $ev_char[$k]['plant_name_text'] = $v['name'];
                }else{
                    $ev_char[$k]['plant_name_text'] = mb_substr($v['name'],0,10,"utf-8")."···";
                }
                $ev_char[$k]['region_text'] = $region;
            }
            $this->china = D("Region")->getChinaArea();
        }

//        P($ev_char);
        $this->assign('ev_char',$ev_char);
        $this->display();
    }


    //生成运营二维码   str_pad(1,8,"0",STR_PAD_LEFT);不足向左补零 例：00000001
    public function createEvcNumber(){
        $id  = I("id");
        $key = substr(I("key_link"),0,4);
        $map['key_link'] = array("like",$key."%");
        $max_evc_number = M("char")->where($map)->max("evc_number");
        if($max_evc_number != ''){
            $data['evc_number'] = str_pad($max_evc_number + 1,12,"0",STR_PAD_LEFT);
            $result = M("char")->where("id='".$id."'")->save($data);
            if($result){
                //执行运营二维码下发指令
                $num = M("char")->where("id='".$id."'")->find();
                $url = 'http://id.dz.tt/index.php?m=content&c=api_v3&a=setEv2Code1&addr='.$num['key_link'].'&ev2code='.$num['evc_number'];
                responseURL($url);
                $return['state'] = 100;
                $return['msg'] = "生成成功！";
            }else{
                $return['msg'] = "生成失败，请重试！";
            }
        }else{
            $data['evc_number'] = $key."00000001";
            $result = M("char")->where("id='".$id."'")->save($data);
            if($result){
                //执行运营二维码下发指令
                $num = M("char")->where("id='".$id."'")->find();
                $url = 'http://id.dz.tt/index.php?m=content&c=api_v3&a=setEv2Code1&addr='.$num['key_link'].'&ev2code='.$num['evc_number'];
                responseURL($url);
                $return['state'] = 100;
                $return['msg'] = "生成成功！";
            }else{
                $return['msg'] = "生成失败，请重试！";
            }
        }
        echo json_encode($return);
        exit;
    }

    //搜索站点
    public function AjaxPlantSearch()
    {
        if (IS_AJAX) {
            
            $mode=I('mode');
            
            if(I('location_s_1') == 110100 || I('location_s_1') == 120100 || I('location_s_1') == 310100 || I('location_s_1') == 500100){
                if(I('location_s_1') == I('location_t_1')-1){
                    $location = I('location_f_1').",".I('location_s_1');
                }else{
                    $location = I('location_f_1').",".I('location_s_1').",".I('location_t_1');
                }
            }else if(I('location_s_1') == I('location_t_1')-1){
                $location = I('location_f_1').",".I('location_s_1');
            }else{
                $location = I('location_f_1').",".I('location_s_1').",".I('location_t_1');
            }
            //echo $location;
            if (!empty($mode)){ $data['plant_mode']=array('eq',$mode);}
            $data['location'] = array('like','%'.$location.'%');
            $site = M("plant")->where($data)->order("id")->select();
            $return = "";
            foreach($site as $v){
                $return .="<span>站点名称：</span><a href='javascript:void(0);' data-nid=".$v[id]." data-pid=".$v[total_ev]." data-dismiss='modal' data-id=".$v[evc_type]." data-plant_mode=".$v[plant_mode]." class='siteSelect'>" . $v[name] . "</a><br/>
                <span style='margin-bottom: 5px;' class='companyAddr'>地　　址：".$v[address]."</span><br/><br/>";
            }
            echo $return;
        }
    }
    //添加电桩
    public function add(){
        if(IS_GET){
            $plant = M("plant")->where("id='".I('id')."'")->field("id,name,evc_type,total_ev,plant_mode")->find();
            $this->plant=$plant;
        }
        if(IS_POST){
//            P($_POST);die;
            for($i=1;$i<=$_POST[recruit_num];$i++)
            {
                $data=$_POST;
                $data['evc_sn']          = $_POST['evc_sn_'.$i];
                $data['charID']          = $_POST['charID_'.$i];
                $data['key_link']        = $_POST['key_link_'.$i];
                $data['s_link']          = $_POST['s_link_'.$i];
                $data['h_link']          = $_POST['h_link_'.$i];
                $data['h_link_port']     = $_POST['h_link_port_'.$i];
                $data['wifi']            = $_POST['wifi_'.$i];
                $data['card_wifi']       = $_POST['card_wifi_'.$i];
                $data['evc_type']        = $_POST['evc_type_'.$i];
                $data['evc_quantity']    = $_POST['evc_quantity_'.$i];
                $data['card_gprg']       = $_POST['card_gprg_'.$i];
                $data['ev_fac_code']     = $_POST['ev_fac_code_'.$i];//厂商
                $data['ev_fac_type1']    = $_POST['ev_fac_type1_'.$i];//设备类型一级
                $data['ev_fac_type2']    = $_POST['ev_fac_type2_'.$i];//设备类型二级
                $data['state_id']        = 0;//默认为空闲状态
                $data['first_online']    = date("Y-m-d H:i:s",time());
                $evc_type                = M("plant")->where("id='".$_POST['ev_plant_id']."'")->field("evc_type,total_ev,total_par")->find();
                if($data['evc_quantity'] == 1){
                    $num['total_ev'] = $evc_type['total_ev'] +1;
                    $num['total_par'] = $evc_type['total_par'] +1;
                    M("plant")->where("id='".$_POST['ev_plant_id']."'")->save($num);
                }else{
                    $num['total_ev'] = $evc_type['total_ev'] +1;
                    $num['total_par'] = $evc_type['total_par'] +2;
                    M("plant")->where("id='".$_POST['ev_plant_id']."'")->save($num);
                }
                $result =M("char")->data($data)->add();
            }
            if($result > 0){
                $this->redirect("Evcharger/index");
            }else{
                $this->error("添加失败，请重试！");
            }
        }
        $this->china = D("Region")->getChinaArea();
        $this->Manu  = D("Fac")->getManufacturer();

        $this->display();
    }

    //查看电桩详细信息
    public function detail(){
        if(IS_GET){
            $data = M("char")->where("id='".$_GET['id']."'")->find();
            $plant = M("plant")->where("id='".$data['ev_plant_id']."'")->field("location,name")->find();
            $region = strsToArray($plant['location']);
            $region_text = D("Region")->where("code='".$region[2]."'")->getField("fullname");
            $data['name'] = $plant['name'];
            $data['location_text'] = $region_text;
            $trademark = M("fac")->where("fac_login_name=".$data['ev_fac_code'])->find();
            $data['trademark']     = $trademark['name'];
            $data['ev_fac_code']   = $trademark['fac_name'];
            $this->data = $data;
        }
        $this->display();
    }
    //批量编辑电桩所属站点
    public function editplant(){
        if(IS_AJAX){
            $charids = strsToArray(I("charids"));
            $plantid = I("plantid");
            $plant   = M("plant")->where("id='".$plantid."'")->find();
            $datas['total_ev']  = $plant['total_ev'] + count($charids);
            $datas['total_par'] = $plant['total_par'] + count($charids);
            $results = M("plant")->where("id='".$plantid."'")->save($datas);
            if($results){
                $map['id'] = array("IN",$charids);
                $data['ev_plant_id'] = $plantid;
                $result = M("char")->where($map)->save($data);
                if($result){
                    $return['state'] = 100;
                    $return['url']   = U('Evcharger/index');
                }else{
                    $return['state'] = 200;
                    $return['msg']   = '保存失败！';
                }
            }else{
                $return['state'] = 200;
                $return['msg']   = '保存失败！';
            }
            echo json_encode($return);
            exit;
        }
        $this->china = D("Region")->getChinaArea();
        $this->display();
    }
    //修改电桩基础信息
    public function update(){
        if(IS_GET){
            $charOne = M("char")->where("id='".I('id')."'")->find();
            $plantOne = M("plant")->where("id='".$charOne['ev_plant_id']."'")->field("name,total_ev")->find();
            $charOne['name'] = $plantOne['name'];
            $charOne['total_ev'] = $plantOne['total_ev'];
            $fac = M("fac")->where("fac_login_name=".$charOne['ev_fac_code'])->find();
            $factory1 = M("device_type")->where("id=".$charOne['ev_fac_type1'])->find();
            $factory2 = M("device_type")->where("id=".$charOne['ev_fac_type2'])->find();
            $charOne['ev_fac_codeText'] = $fac['name'].",".$factory1['name'].",".$factory2['name'];
            $charOne['fac'] = $fac['id'].",".$factory1['id'].",".$factory2['id'];
            $this->charOne  = $charOne;
            /*if(!empty($charOne['ev_fac_code'])){
                $this->Manu  = D("Fac")->getManufacNew($charOne['ev_fac_code']);
            }else{*/
                $this->Manu  = D("Fac")->getManufacturer();
//            }
        }
        if(IS_POST){
//            P($_POST);die;
            $char = M("char")->where("id='".I('id')."'")->find();
            if($char['ev_plant_id'] != I('ev_plant_id')){
                $plant_1 = M("plant")->where("id='".$char['ev_plant_id']."'")->find();
                if($plant_1['total_ev'] != '' && $plant_1['total_ev'] != 0){
                    $maps['total_ev'] = $plant_1['total_ev'] - 1;
                    if($char['evc_quantity'] == 1){
                        $maps['total_par']   = $plant_1['total_par'] - 1;
                    }else{
                        $maps['total_par']   = $plant_1['total_par'] - 2;
                    }
                    M("plant")->where("id='".$char['ev_plant_id']."'")->save($maps);
                }
                $plant = M("plant")->where("id=".I('ev_plant_id'))->find();
                $map['total_ev']    = $plant['total_ev'] + 1;
                if(I('evc_quantity') == 1){
                    $map['total_par']   = $plant['total_par'] +1;
                }else{
                    $map['total_par']   = $plant['total_par'] +2;
                }
                M("plant")->where("id=".I('ev_plant_id'))->save($map);
            }
            $data = $_POST;
            if($char['evc_number'] != $data['evc_number']){
                //运营二维码发生变更，执行运营二维码下发指令
                $url = 'http://id.dz.tt/index.php?m=content&c=api_v3&a=setEv2Code1&addr='.$data['key_link'].'&ev2code='.$data['evc_number'];
            }
            if($_POST['ev_fac_code'] == '' || $_POST['ev_fac_code'] == 0){
                $arr = strsToArray($_POST['fac']);
                $data['ev_fac_code'] = M("fac")->where("id='".$arr[0]."'")->getField("fac_login_name");
                $data['ev_fac_type1'] = $arr[1];
                $data['ev_fac_type2'] = $arr[2];
            }else{
                $data['ev_fac_code'] = M("fac")->where("id='".I('ev_fac_code')."'")->getField("fac_login_name");
            }
            $result = M("char")->where("id='".$_POST['id']."'")->save($data);
            if($result > 0){
                responseURL($url);
                $this->redirect("Evcharger/index");
            }else{
                $this->error("保存失败，请重试！");
            }
        }
        $this->china = D("Region")->getChinaArea();
//        $this->Manu  = D("Fac")->getManufacturer();
        $this->display();
    }
    //删除当前电桩
    public function  delChar(){
       if(IS_GET){
            $charOne = M("char")->where("id='".$_GET['id']."'")->find();
            D("State")->where("key_link = '".$charOne['key_link']."'")->delete();
           $evc_type = M("plant")->where("id='".$charOne['ev_plant_id']."'")->find();
            if($charOne['evc_quantity'] == 1){
                $num['total_ev'] = $evc_type['total_ev'] -1;
                $num['total_par'] = $evc_type['total_par'] -1;
            }else{
                $num['total_ev'] = $evc_type['total_ev'] -1;
                $num['total_par'] = $evc_type['total_par'] -2;
            }
           M("plant")->where("id='".$charOne['ev_plant_id']."'")->save($num);
            $result = M("char")->where("id='".$_GET['id']."'")->delete();
           if($result){
               echo 1;
           }else{
               echo 2;
           }
       }else{
           $charids = strsToArray($_POST['charids']);
           $map['id'] = array("IN",$charids);
           $chars = M("char")->where($map)->select();
           foreach($chars as $v){
               D("State")->where("key_link = '".$v['key_link']."'")->delete();
               $evc_type = M("plant")->where("id='".$v['ev_plant_id']."'")->find();
               if($v['evc_quantity'] == 1){
                   $num['total_ev'] = $evc_type['total_ev'] -1;
                   $num['total_par'] = $evc_type['total_par'] -1;
               }else{
                   $num['total_ev'] = $evc_type['total_ev'] -1;
                   $num['total_par'] = $evc_type['total_par'] -2;
               }
               M("plant")->where("id='".$v['ev_plant_id']."'")->save($num);
               $result = M("char")->where("id='".$v['id']."'")->delete();
           }
           if($result){
               $return['state'] = 100;
               $return['msg']   = '删除成功！';
           }else{
               $return['state'] = 200;
               $return['msg']   = '删除失败！';
           }
           echo json_encode($return);
           exit;
       }
    }   
}